# coding=utf-8
# !/usr/bin/python
# by eaudouce
import os, sys, json, requests, time, base64, random, hashlib, math, urllib.parse
sys.path.append('..')
from base.spider import Spider
from pprint import pprint

class Spider(Spider):  # 元类 默认的元类 type
    site_name = 'xk_哔哩'
    host = 'https://www.bilibili.com/'
    cookies = ''
    w_webid = ''
    headers = {
        #'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate',
        #'Accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,it;q=0.5,pl;q=0.4',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0'
    }
    config = {
        'player': {},
        'filter': {
            'up_all': [
                {
                    'key': 'order',
                    'name': '排序',
                    'value': [{'n': i.split(',')[0], 'v': i.split(',')[1]} for i in '综合排序,#最多播放,click#最新发布,pubdate'.split('#')]
                }
            ],
            '0#怪诞小镇': [
                {
                    'key': 'subkey',
                    'name': '季数',
                    'value': [{'n': '全部', 'v': ''}] + [{'n': i, 'v': i} for i in '第一季#第二季'.split('#')]
                }
            ],
            '0#星蝶公主': [
                {
                    'key': 'subkey',
                    'name': '季数',
                    'value': [{'n': '全部', 'v': ''}] + [{'n': i, 'v': i} for i in '第一季#第二季#第三季#第四季'.split('#')]
                }
            ]
        },
        'class': [
            {'type_name': 'UP:巡游轨迹', 'type_id': '437573432#巡游轨迹'},
            {'type_name': 'UP:周大锤', 'type_id': '3546708063554190#恭喜周大锤'},
            {'type_name': '动画:怪诞小镇', 'type_id': '0#怪诞小镇'},
            {'type_name': '动画:星蝶公主', 'type_id': '0#星蝶公主'}
        ]
    }

    def getName(self):
        return self.site_name

    def init(self, extend=''):
        #print('============{0}============'.format(extend))
        pass

    def isVideoFormat(self, url):
        pass

    def manualVideoCheck(self):
        pass

    def homeContent(self, filter):
        result = {'class': self.config['class']}
        filters = {}
        if filter:
            for t in self.config['class']:
                if self.config['filter'].get(t['type_id']):
                    filters[t['type_id']] = self.config['filter'][t['type_id']]
                elif not t['type_id'].startswith('0#'):
                    filters[t['type_id']] = self.config['filter']['up_all']
            result['filters'] = filters
        return result

    def homeVideoContent(self):
        return {'list': []}

    def getCookie(self):
        rsp = self.fetch(self.host, headers=self.headers)
        self.cookies = requests.utils.dict_from_cookiejar(rsp.cookies)
        return self.cookies

    def categoryContent(self, tid, pg, filter, extend):
        limit = 30
        pg = int(pg)
        result = {
            'list': [],
            'page': pg,
            'pagecount': 0,
            'limit': limit,
            'total': 0
        }
        mid, key = tid.split('#', 1)
        mid = int(mid)
        if len(str(extend.get('subkey', ''))) > 0:
            key += ' ' + extend['subkey']
        params = {
            'key': urllib.parse.quote(key, encoding='UTF-8'),
            'page': pg,
            'offset': (pg-1)*limit,
            'order': ''
        }
        if len(str(extend.get('order', ''))) > 0:
            params['order'] = '&order='+extend['order']
        #print(params)

        url = 'https://api.bilibili.com/x/web-interface/search/type?search_type=video&keyword={key}&page={page}&page_size=42&dynamic_offset={offset}{order}'.format(**params)
        if len(self.cookies) <= 0:
            self.getCookie()
        headers = self.headers
        headers['Referer'] = 'https://search.bilibili.com/all?keyword={key}&search_source=3&page={page}&o={offset}'.format(**params)
        rsp = self.fetch(url, cookies=self.cookies, headers=headers)
        content = rsp.text
        jo = json.loads(content)
        #pprint(jo)
        if jo['code'] != 0:
            return
        jo = json.loads(content)
        videos = []
        vodList = jo['data']['result']
        for vod in vodList:
            if vod['is_pay'] != 0 or (mid > 0 and vod['mid'] != mid):
                continue
            aid = str(vod['aid']).strip()
            title = vod['title'].replace('<em class="keyword">', '').replace('</em>', '').replace('&quot;', '"')
            img = self.genFullUrl(vod['pic'].strip(), self.host)
            remark = time.strftime('%Y-%m-%d 时长', time.localtime(vod['pubdate'])) + self.formatDuration(vod['duration'])
            videos.append({
                'vod_id': aid,
                'vod_name': title,
                'vod_pic': img,
                'vod_remarks': remark
            })
        pagecount = int(jo['data']['numPages'])
        total = int(jo['data']['numResults'])
        #print(len(videos))

        result['list'] = videos
        result['page'] = pg
        result['pagecount'] = pagecount
        result['limit'] = limit
        result['total'] = total
        return result

    def detailContent(self, array):
        aid = array[0]
        url = 'https://api.bilibili.com/x/web-interface/view?aid={0}'.format(aid)
        if len(self.cookies) <= 0:
            self.getCookie()
        rsp = self.fetch(url, headers=self.headers, cookies=self.cookies)
        jRoot = json.loads(rsp.text)
        jo = jRoot['data']
        title = jo['title'].replace('<em class="keyword">', '').replace('</em>', '').replace('&quot;', '"')
        pic = jo['pic']
        desc = jo['desc']
        timeStamp = jo['pubdate']
        timeArray = time.localtime(timeStamp)
        year = str(time.strftime('%Y', timeArray))
        director = jo['owner']['name']
        typeName = jo['tname']
        remark = self.formatDuration(jo['duration'])
        vod = {
            'vod_id': aid,
            'vod_name': title,
            'vod_pic': pic,
            'type_name': typeName,
            'vod_year': year,
            'vod_area': '',
            'vod_remarks': remark,
            'vod_actor': '',
            'vod_director': director,
            'vod_content': desc
        }
        ja = jo['pages']
        playUrl = ''
        for tmpJo in ja:
            cid = tmpJo['cid']
            part = tmpJo['part'].replace('#', '-')
            playUrl += '{0}${1}_{2}#'.format(part, aid, cid)

        vod['vod_play_from'] = self.site_name
        vod['vod_play_url'] = playUrl.strip('#')

        result = {
            'list': [
                vod
            ]
        }
        return result

    def searchContent(self, key, quick):
        return {'list': []}

    def playerContent(self, flag, id, vipFlags):
        result = {}

        ids = id.split('_')
        url = 'https://api.bilibili.com:443/x/player/playurl?avid={0}&cid={1}&qn=116'.format(ids[0], ids[1])
        if len(self.cookies) <= 0:
            self.getCookie()
        headers = self.headers
        headers['Referer'] = self.host
        rsp = self.fetch(url, cookies=self.cookies, headers=headers)
        jRoot = json.loads(rsp.text)
        jo = jRoot['data']
        ja = jo['durl']

        maxSize = -1
        position = -1
        for i in range(len(ja)):
            tmpJo = ja[i]
            if maxSize < int(tmpJo['size']):
                maxSize = int(tmpJo['size'])
                position = i

        url = ''
        if len(ja) > 0:
            if position == -1:
                position = 0
            url = ja[position]['url']

        cookies_str = ''
        for i in self.cookies:
            cookies_str += i + '=' + self.cookies[i] + '; '
        headers['Cookie'] = cookies_str
        result['parse'] = 0
        result['playUrl'] = ''
        result['url'] = url
        result['header'] = headers
        result['contentType'] = 'video/x-flv'
        return result

    def localProxy(self, param):
        return [200, 'video/MP2T', action, '']

    def formatDuration(self, duration):
        result = []
        if str(duration).isdigit() == False:
            return duration
        duration = int(duration)
        for i in range(0, 3):
            duration = divmod(duration, 60)
            result.insert(0, '{}'.format(duration[1]).zfill(2))
            duration = duration[0]
        if result[0] == '00':
            return ':'.join(result[1:])
        else:
            return ':'.join(result).lstrip('0')

    def genFullUrl(self, url, page_url):
        url = url.strip()
        page_url = page_url.strip()
        result = urllib.parse.urlparse(page_url)
        if len(url) < 1:
            return url
        elif url.startswith('http://') or url.startswith('https://'):
            return url
        elif url.startswith('//'):
            return result.scheme + ':' + url
        elif url.startswith('/'):
            return result.scheme + '://' + result.netloc + url
        elif url.startswith('./'):
            return result.scheme + '://' + result.netloc + '/'.join(result.path.split('/')[:-1]).rstrip('/') + '/' + url[2:]
        elif url.startswith('../'):
            url_arr = url.split('../')
            pos = -len(url_arr)
            return result.scheme + '://' + result.netloc + '/'.join(result.path.split('/')[:pos]).rstrip('/') + '/' + url_arr[-1]
        else:
            return result.scheme + '://' + result.netloc + '/'.join(result.path.split('/')[:-1]).rstrip('/') + '/' + url
